<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>迭代器</title>
  <!-- 
    iterator 意在提供一种统一的，能够处理所有不同的数据结构的接口机制，因此只要任意的对象上实现了 Symbol.iterator 就可以使用 for of 来遍历
   -->
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
    }
  </style>
</head>

<body>
  <div></div>
</body>
<script>
  "use strict"; {
    let obj = {
      [Symbol.iterator]() {
        let i = 0;
        return {
          next: () => {
            if (i < 5) {
              return { value: i++, done: false };
            } else {
              return { done: true };
            };
          }
        };
      }
    };

    // 遍历实现的迭代器
    for (let k of obj) {
      console.log(k);
    };


    // 甚至还可以和 Generator 语法结合
    const obj1 = {
      *[Symbol.iterator]() {
        yield 0;
        yield 1;
        yield 2;
        yield 3;
        yield 4;
      }
    };

    for (let i of obj1) {
      console.log(`i ==`, i);
    };
  };
</script>

</html>